<?php
require_once("../includes/config.php"); 
  if (!isset($_REQUEST['cid']))
  {
  $_SESSION['error_message'] = "برجاء اختيار شركة";
  header("Location:coprice.php");
  die();
  }
  if(isset($_POST['add-periods'],$_POST['pidz']) && $_POST['add-periods'] == 1)
  {
  	if ($_POST['pidz']!="")
	{
	$pidz=explode("|",$_POST['pidz']);
	foreach ($pidz as $pid)
	{
	$from="from-".$pid;
	$to="to-".$pid;
	$del="del-".$pid;	
	if (isset($_POST["$from"],$_POST["$to"])&&!isset($_POST["$del"]))
	{
	$result = query("UPDATE `co_periods` SET period_from = ?, period_to = ? where period_id=? and owner_id=? and co_id=?",$_POST["$from"],$_POST["$to"],$pid,$_SESSION['id'],$_REQUEST['cid']);     
	}
	elseif(isset($_POST["$del"]))
	{
	codelperiod($pid,$_SESSION['id'],$_REQUEST['cid']);
	}
	}
	    $_SESSION['success_message'] = "تم تحديث فترات الايجار";
  }
  
  }
  elseif(isset($_POST['value'],$_REQUEST['cid']))
  {
	//Updating the specific value updated by user either daily weekly monthly
	if (isset($_POST['field']))
	{
	cosetpp($_POST['id'],$_POST['pid'],$_POST['field'],$_POST['value'],$_REQUEST['cid']);
	    echo $_POST['value'];
	}
	die();
  }
  elseif (isset($_POST['newperiod'],$_REQUEST['cid'])&&is_numeric($_REQUEST['cid']))
  {
  query("INSERT INTO `co_periods` (`owner_id`,`co_id`,`apt`, `period_from`, `period_to`) VALUES (?,?,NULL, '', '')",$_SESSION['id'],$_REQUEST['cid']);
  $_SESSION['success_message'] = "تم اضافة فترة جديدة";
  }
  
  $periods = query("SELECT * FROM `co_periods` WHERE `owner_id`=? AND `co_id`=?",$_SESSION['id'],$_REQUEST['cid']);
  $aparts = query("SELECT * FROM apartments WHERE owner_id = ?",$_SESSION['id']);
  render("settings/setcoprice.php",array("title"=>"إعدادات الاسعار","periods"=>$periods,"aparts"=>$aparts,"cid"=>$_REQUEST['cid']));
  ?>